<?php

class TeamController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function actions() {
		return array (
				'approve' => array ('class' => 'CViewAction'),
				
				'file' => array ('class' => 'CViewAction') 
				);
	}
	
	
	public function actionFile($filename, $url) {
		
		return Yii::app()->getRequest()->sendFile($filename, @file_get_contents($url));
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','file','index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','approve'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionApprove($id) {
		if(Yii::app()->request->isPostRequest) {
			
			$team = $this->loadModel($id);
			$team->status = 'ATIVO';
			$team->save();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(array('view', 'id'=> $id));
		} else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		
		if(!is_dir(Yii::getPathOfAlias('webroot').'/images')) {
			mkdir(Yii::getPathOfAlias('webroot').'/images');
			chmod(Yii::getPathOfAlias('webroot').'/images');//, 0755);
		}
		
		$formats = 'jpg|gif|png|pdf|doc|odt|docx|xls|xlsx';
		
		$model=new Team;
		$contacts = array();
		$hasContact = true;
		$file = new File();
		$hasFiles = true;
		$hasPhoto = true;
		$images = array();
		$foto = array();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['Team'])) {
			$contacts = $this->verifyContacts($contacts);
			$hasContact = Utils::hasContent($contacts);
			date_default_timezone_set('UTC');
			
			$model->attributes = $_POST['Team'];
			$images = CUploadedFile::getInstancesByName('filenames');
			
			$foto = CUploadedFile::getInstancesByName('foto');
			
			$model->owner = $_SESSION['owner'];
			$model->owner_id = $_SESSION['owner']->id;
			$model->setDateTime(date("d-M-y"));
			$model->status = "EM APROVAÇÃO";
			
			$hasFiles = isset($images) && count($images) > 0;
			$hasPhoto = isset($foto) && count($foto) > 0;
			
			if($model->validate() && $hasFiles && $hasPhoto) {
				
				$model->save();
				$this->saveContacts($contacts, $model->id);
				
				foreach ($images as $image => $pic) {
					
					if(!empty($pic)) {
                    	$pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name);
                        // add it to the main model now
                        $file = new File();
                        $file->url = Yii::getPathOfAlias('webroot').'/images/'.$pic->name;
                        $file->filename = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model
                        $file->relation_id = $model->id; // this links your picture model to the main model (like your user, or profile model)
                        $file->type = "TEAM";
                        $file->save();
					}
                }
                
                foreach($foto as $path => $pic) {
                	
                	if(!empty($pic)) {
                		$extension = pathinfo($pic->name, PATHINFO_EXTENSION);
                		$pic->saveAs(Yii::getPathOfAlias('webroot') . '/images/' . Team::$photo_name . $model->name . '.' . $extension);
                		$file = new File();
                		$file->url = Yii::getPathOfAlias('webroot') . '/images/' . Team::$photo_name . $model->name .  '.' . $extension;
                		$file->filename = Team::$photo_name . $model->name .  '.' . $extension;
                		$file->relation_id = $model->id;
                		$file->type="TEAM";
                		$file->save();
                	}
                	
                }
                
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'contacts'=>$contacts,
			'hasContact'=>$hasContact,
			'file'=>$file,
			'formats' => $formats,
			'images'=>$images,
			'foto'=>$foto,
			'hasFiles' => $hasFiles,
			'hasPhoto' => $hasPhoto,
		));
	}
	
	private function saveFiles($file, $id) {
		foreach($file->filename as $filename) {
			$fileobject = CUploadedFile::getInstanceByName($filename);
			echo $fileobject->name;
			if(!empty($fileobject)) {
				$pic->saveAs(Yii::app()->basePath.'/../images/'.$fileobject->name);
				$file = new File();
				$file->filename = $fileobject->name;
				$file->type = "TEAM";
				$file->relation_id = $id;
				$file->save();
				
				echo "file ".$fileobject->name." saved";
			} else {
				echo "Arquivo não encontrado";
			}
		}
	}

	/**
	 * Verifies the added contacts
	 * 
	 * @param unknown $contacts
	 * @return Source
	 */
	private function verifyContacts($contacts) {
			
		if(isset($_POST['Contact'])) {
			foreach($_POST['Contact'] as $post) {
				$contact = new Contact;
				$contact->attributes = $post;
				if($contact->contact != null && trim($contact->contact) != "") {
					$contacts[] = $contact;
				}
			}
		}
		return $contacts;
	}
	
	/**
	 * Save the contacts
	 * 
	 * @param unknown $contacts
	 * @param unknown $idTeam
	 */
	private function saveContacts($contacts, $idTeam) {
		
		Contact::model()->deleteAllByAttributes(array('team_id'=> $idTeam));
		
		foreach ($contacts as $contact) {
			$contact->team_id = $idTeam;
			$contact->save();
		}
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model=$this->loadModel($id);
		$hasContact = true;
		$foto = array(Utils::getTeamPhoto($model));
		
		$contacts = Contact::model()->findAllByAttributes(array('team_id'=>$model->id));
		

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Team']))
		{
			$contacts = $this->verifyContacts(array());
			
			$hasContact = Utils::hasContent($contacts);
				
			date_default_timezone_set('UTC');
			
			$model->attributes=$_POST['Team'];
			
			if($model->validate()) {
				$model->save();
				$this->saveContacts($contacts, $model->id);
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
			'contacts'=>$contacts,
			'hasContact'=>$hasContact,
			'foto'=>$foto,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$model=new Team('search');
		$dataProvider=new CActiveDataProvider('Team');
		$this->render('index',array(
			'dataProvider'=>$model->search(),
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model=new Team('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Team']))
			$model->attributes=$_GET['Team'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Team::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='team-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
